#!/bin/bash
set -e

# Prevent owner issues on mounted folders, if desired
	chown -R oracle:dba /u01/app/oracle

rm -f /u01/app/oracle/product
ln -s /u01/app/oracle-product /u01/app/oracle/product

export CHARACTER_SET="ZHS16GBK"
export CHARSET_MOD="NLS_LANG=.$CHARACTER_SET"
export CHARSET_INIT="-characterSet $CHARACTER_SET"


case "$1" in
	'')
		#Check for mounted database files
		if [ "$(ls -A /u01/app/oracle/oradata 2>/dev/null)" ]; then
			echo "found files in /u01/app/oracle/oradata Using them instead of initial database"
			echo "$ORACLE_SID:$ORACLE_HOME:N" >> /etc/oratab
			chown oracle:dba /etc/oratab
			chmod 664 /etc/oratab
			rm -rf /u01/app/oracle-product/12.1.0/db1/dbs
			ln -s /u01/app/oracle/dbs /u01/app/oracle-product/12.1.0/db1/dbs
			#Startup Database
			su oracle -c "/u01/app/oracle/product/12.1.0/db1/bin/tnslsnr &"
			su oracle -c 'echo startup\; | $ORACLE_HOME/bin/sqlplus -S / as sysdba'
		else
			echo "Database not initialized. Initializing database."
 
			#printf "Setting up:\nprocesses=$processes\nsessions=$sessions\ntransactions=$transactions\n"
			set +e
			mv /u01/app/oracle-product/12.1.0/db1/dbs /u01/app/oracle
			set -e

			ln -s /u01/app/oracle/dbs /u01/app/oracle-product/12.1.0/db1/dbs

			echo "Starting tnslsnr"
			su oracle -c "$ORACLE_HOME/bin/tnslsnr &"
			#create DB for SID: $ORACLE_SID
			su oracle -c "$ORACLE_HOME/bin/dbca -silent -createDatabase -templateName General_Purpose.dbc -gdbname $ORACLE_SID -sid $ORACLE_SID -responseFile NO_VALUE $CHARSET_INIT -totalMemory $DBCA_TOTAL_MEMORY -emConfiguration LOCAL -pdbAdminPassword oracle -sysPassword oracle -systemPassword oracle"
		fi

		echo "Database ready to use. Enjoy! ;)"

		##
		## Workaround for graceful shutdown.
		##
		while [ "$END" == '' ]; do
			sleep 1
			trap "su oracle -c 'echo shutdown immediate\; | $ORACLE_HOME/bin/sqlplus -S / as sysdba'" INT TERM
		done
		;;

	*)
		echo "Database is not configured. Please run '/entrypoint.sh' if needed."
		exec "$@"
		;;
esac

